class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy, :do, :do_exec]

  # GET /projects
  # GET /projects.json
  def index
    @projects = Project.all
  end

  def do
    cmd_texts = {
        'full-restart'=> '全流程重启',
        'checkout'=> '切分支…',
    }
    @html_title = cmd_texts[params[:command]]
    @commands = [:pull, :bundle, :migrate, :assets, :start_server]
    render layout: 'modal'
  end

  def do_exec
    if params[:command]=='fetch'
      @project.update_branch_text!
      return show_js_notice '操作成功！'
    end

    if params[:commands].is_a?(Array) && params[:commands][0]=='checkout' && params[:branch].present?
      params[:commands][0] = ['checkout', params[:branch]]
    end
    ExecWorker.perform_async 1, params[:commands], current_user.id
    respond_to do |format|
      format.js
    end
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = Project.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = Project.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:name, :full_path, :name_a_host, :pid_path, :restart_command, :restart_sh, :start_command, :stop_command, :visit_url, :status_text, :notes, :string)
    end
end
